package com.jthink.module.comments;

import com.jthink.common.model.Account;
import com.jthink.common.model.ArticleComment;
import com.jfinal.aop.Inject;
import com.jfinal.core.Path;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jthink.module.base.BaseFrontController;
import com.jthink.module.kit.SensitiveWordsKit;
import com.jthink.module.template.TemplateManager;

@Path(value = "/article/comments")
public class ArticleCommentController extends BaseFrontController {
    @Inject
    ArticleCommentService srv;

    public void save() {
        if (notLogin()) {
            renderJson(Ret.fail( "登录后才可以评论"));
            return;
        }
        ArticleComment comment = getBean(ArticleComment.class, "comment");
        if (!StrKit.isBlank(comment.getContent()) && SensitiveWordsKit.checkSensitiveWord(comment.getContent()) != null) {
            renderJson(Ret.fail( "回复内容不能包含敏感词"));
            return;
        }
        Ret ret = srv.save(getLoginAccountId(), comment);
        if(ret!=null && ret.isOk()){
            // 注入 nickName 与 avatar 便于 renderToString 生成 commentItem html 片段
            Account loginAccount = getLoginAccount();
            ret.set("loginAccount", loginAccount);
            // 用模板引擎生成 HTML 片段 commentItem
            String commentItem = renderToString(TemplateManager.me().getCurrentTemplate().getRelativePath() + "/_comment_item.html", ret);
            ret.set("commentItem", commentItem);
        }
        renderJson(ret);
    }

    public void delete() {
        int id = getInt("id");
        srv.delete(id);
        renderJson(Ret.ok("删除成功").set("id", id));
    }
}
